<?php
namespace app\index\controller;

use app\common\model\Activity;
use app\common\model\Apply;
use app\common\model\ActivityVisit;
use app\common\model\Record;
use app\index\model\Jssdk;
use app\common\model\ShareVoucher;
use app\common\model\RecordBrokerage;
use app\common\model\User;
use app\common\model\UserAccount;
use app\common\model\Ad;

class Index extends Base
{
    public function index()
    {
        $keyword = $this->request->param('keyword');
        $sort = $this->request->param('sort', 'create_time');

        // 统计
        $participant = Apply::where(['aid' => $this->activity->id])->count();
        $voteTotal = Apply::where(['aid' => $this->activity->id])->sum('poll');
        $visitTotal = ActivityVisit::where(['aid' => $this->activity->id])->count();

        // 访问首页添加统计量
        if($visit = ActivityVisit::where(['aid' => $this->activity->id, 'user_id' => $this->user->id])->find()) {
            $visit->num++;
            $visit->save();
        } else {
            $data = [
                'aid' => $this->activity->id,
                'user_id' => $this->user->id,
                'ip' => $this->request->ip(),
                'create_time' => time()
            ];
            (new ActivityVisit())->insert($data);
        }

        // 显示需要显示的参赛选手
        $map = [];
        $map['aid'] = $this->activity->id;
        $map['status'] = ['neq', 2];
        $keyword && $map['baby_name'] = ['like','%'.$keyword.'%'];
        $apply = Apply::where($map)->order($sort . ' desc')->select();

        // 首页弹框广告
        $where = [
            'activity_id' => ['in', [0, $this->activity->id]],
            'start_time'  => ['lt', time()],
            'end_time'    => ['gt', time()],
        ];
        $ad = Ad::where($where)->order('id desc')->find();

        $this->assign('ad', $ad);
        $this->assign('statisticsTotal', [
            'participant' => $participant,
            'voteTotal' => $voteTotal,
            'visitTotal' => $visitTotal
        ]);

//        $jssdk = new Jssdk();
//        $this->assign('signPackage', $jssdk->GetSignPackage());
        $this->assign('apply', $apply);
        $this->assign('sort', $sort);
        $this->assign('keyword', $keyword);
        return $this->fetch(':index');
    }

    public function detail()
    {
        $applyId = $this->request->param('apply_id');
        $apply = Apply::get($applyId);
        $rank = $apply->getRank();      // 名次

        // 收集前八名以及当前选手
        $player = [];
        // 获取给该宝宝投票的前八名
        $frontRank = Record::alias('r')->join('user u', 'u.id = r.user_id')
                     ->where(['r.apply_id' => $applyId])
                     ->field('count(*) as num, u.avatar')
                     ->order('count(*) desc')
                     ->limit(0,8)
                     ->group('r.user_id')->select();
        $i = 1;
        foreach ($frontRank as $key => $val) {
            $frontRank[$key]['rank'] = $i;
            $i++;
            if($i > 3) break;
        }
        $frontRank = array_reverse($frontRank);
//        $frontRank = Apply::where(['aid' => $this->activity->id])->order('poll desc')->limit(0,8)->select();
//        $frontRank = array_reverse($frontRank);
//        foreach($frontRank as $val) {
//            $player[] = $val->user_id;
//        }

        // 获取投票与拉票的人
        $record = Record::where(['apply_id' => $applyId, 'user_id' => ['neq', $apply['user_id']]])
                  ->field('user_id, type')->group('user_id')->select();
        foreach($record as $key => $val) {
            if(!in_array($val->user_id, $player)) $player[] = $val->user_id;
        }
        if(!in_array($apply->user_id, $player)) $player[] = $apply->user_id;
        $voter = User::where(['id' => ['in', $player]])->column('nickname, avatar', 'id');
        foreach($record as $key => $val) {
            $record[$key]['nickname'] = isset($voter[$val->user_id]) ? $voter[$val->user_id]['nickname'] : '';
            $record[$key]['avatar'] = isset($voter[$val->user_id]) ? $voter[$val->user_id]['avatar'] : '';
        }

        // 拉票所需
        $jssdk = new Jssdk();
        $this->assign('signPackage', $jssdk->GetSignPackage());

        $this->assign('apply', $apply);
        $this->assign('rank', $rank);
        $this->assign('voter', $voter);
        $this->assign('frontRank', $frontRank);
        $this->assign('record', $record);
        return $this->fetch();
    }

    public function shareSuccess()
    {
        $applyId = $this->request->post('apply_id');
        $data = [
            'user_id' => $this->user->id,
            'date' => date('Ymd', time()),
            'type' => 2,
            'apply_id' => $applyId,
        ];
        // 拉票记录
        if(!(new Record())->add($data)) return $this->jsonFail('网络错误');
        // 申请人
        $apply = Apply::get($applyId);
        $applyUser = User::get($apply->user_id);    // 参与者
        $applyAccount = $applyUser->account;        // 参与者账户
        $brokerage = $apply->brokerage;             // 佣金设置

        if($applyUser->id == $this->user->id) return $this->jsonSuccess('分享成功', ['code' => 1, 'msg' => '本人分享']);
        // 判断余额是否充足
        if($applyAccount->balance < $brokerage->min_money) return $this->jsonSuccess('投票成功', ['code' => 2, 'msg' => '余额不足']);

        // 判断之前是否投过票或分享过
        $recordBrokerage = RecordBrokerage::get(['user_id' => $this->user->id, 'apply_id' => $applyId]);

        // 之前分享过，未点赞
        if($recordBrokerage) {
            // 发放红包
            if(strtotime($recordBrokerage['share_time']) != 0) return $this->jsonSuccess('分享成功', ['code' => 3, 'msg' => '已领取过该红包']);
            try{
                if($recordBrokerage->share_amount > $applyAccount->balance)
                    $recordBrokerage->share_amount = $applyAccount->balance;
                (new UserAccount())->activityEdit($recordBrokerage->share_amount, $this->user->account, $applyAccount, 0);
                $recordBrokerage->share_time = time();
                $recordBrokerage->save();
                return $this->jsonSuccess('分享成功', ['code' => 4,
                    'money' => $recordBrokerage->vote_amount,
                    'baby_name'  => $apply->baby_name,
                    'picture' => $apply->picture,
                    'rank' => $apply->getRank()
                ]);
            } catch (\Exception $e) {
                return $this->jsonError($e->getMessage());
            }
        }

        // 之前未点赞也未分享
        try{
            $maxMoney = min($applyAccount->balance, $brokerage->max_money);
            $brokerageAmount = mt_rand($brokerage->min_money * 100, $maxMoney * 100) / 100;
            $data = ['user_id' => $this->user->id, 'apply_id' => $applyId];
            $result = (new RecordBrokerage())->allot($brokerage, $brokerageAmount, $data, 0);
            (new UserAccount())->activityEdit($result['share_amount'], $this->user->account, $applyAccount);
            return $this->jsonSuccess('投票成功', ['code' => 4,
                'money' => $result['share_amount'],
                'baby_name'  => $apply->baby_name,
                'picture' => $apply->picture,
                'rank' => $apply->getRank()
            ]);
        } catch (\Exception $e) {
            return $this->jsonError($e->getMessage());
        }
    }

    public function rank()
    {
        $apply = Apply::where(['aid' => $this->activity->id])->order('poll desc')->select();
        $this->assign('apply', $apply);
        return $this->fetch();
    }
}
